package cn.com.kh;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.File;
import java.io.FileInputStream;

public class PDFHelper {
	private static final Log log = LogFactory.getLog(PDFHelper.class);

	public static void main(String[] args) throws Exception {

		// 转换PDF测试
		System.out.println(convertPDF("/Users/lijt/Documents/民生测试/html1.html", "/Users/lijt/Documents/民生测试/pdf-1.pdf"));
		System.out.println(convertPDF("/Users/lijt/Documents/民生测试/html2.html", "/Users/lijt/Documents/民生测试/pdf-2.pdf"));

		// 合并PDF测试
		String fillTemplate1 = "/Users/lijt/Documents/民生测试/pdf-1.pdf";
		String fillTemplate2 = "/Users/lijt/Documents/民生测试/pdf-2.pdf";
		List<String> st = new ArrayList<>();
		st.add(fillTemplate1);
		st.add(fillTemplate2);
		combinPdf(st, "/Users/lijt/Documents/民生测试/pdf-8.pdf");

		// 添加水印测试
		String targetPath = "/Users/lijt/Documents/民生测试/pdf_temp.pdf";
		String watermarkPath = "/Users/lijt/Documents/民生测试/123.png";
		addPdfMark("/Users/lijt/Documents/民生测试/pdf-3.pdf", targetPath, watermarkPath, 400, 100, 20);

	}

	/**
	 * 转换为PDF
	 * 
	 * @param sourceFilePath 待合并文件路径
	 * @param targetFilePath 转化后目标文件
	 * @return 操作成功或失败
	 */
	public static boolean convertPDF(String sourceFilePath, String targetFilePath) {

		log.debug("PDFHelper.convertPDF 被调用参数信息--" + "sourceFilePath:" + sourceFilePath + " targetFilePath:" + targetFilePath);
		long startTime, endTime;

		startTime = System.currentTimeMillis();
		boolean isSucc = false;

		String doCommand = getProperty.get("SysCommand") + " " + sourceFilePath + " " + targetFilePath;
		log.debug("PDFHelper.convertPDF doCommand:" + doCommand);

		try {
			Process process = Runtime.getRuntime().exec(doCommand);
			int exitValue = process.waitFor();
			if (0 != exitValue) {
				log.error("PDFHelper.convertPDF Call Shell Failed. Error Code Is:" + exitValue);
				isSucc = false;
			} else {
				log.debug("PDFHelper.convertPDF Call Shell Succ. Succ Code Is:" + exitValue);
				File dirAll = new File(targetFilePath);
				// 检查目标文件是否存在
				if (!dirAll.exists()) {
					isSucc = false;
				} else {
					isSucc = true;
				}
			}

		} catch (Throwable e) {
			isSucc = false;
			log.error("PDFHelper.convertPDF Call Shell Failed ", e);

		} finally {
			endTime = System.currentTimeMillis();
			log.debug("PDFHelper.convertPDF Return Result:" + isSucc + " UseTime:" + (endTime - startTime) + "(ms)");
		}
		return isSucc;
	}

	/**
	 * PDF增加水印方法
	 * 
	 * @param InPdfFile     待合并PDF文件
	 * @param outPdfFile    添加后目标文件
	 * @param markImagePath 水印图片路径
	 * @param xCoord        X轴布局
	 * @param yCoord        Y轴布局
	 * @param scalePercent  缩放比例
	 * @return 操作成功或失败
	 */
	public static boolean addPdfMark(String InPdfFile, String outPdfFile, String markImagePath, int xCoord, int yCoord, int scalePercent) {

		log.debug("PDFHelper.addPdfMark 调用参数信息--" + " InPdfFile:" + InPdfFile + " outPdfFile:" + outPdfFile + " markImagePath:" + markImagePath + " xCoord:" + xCoord + " yCoord:" + yCoord + " scalePercent:" + scalePercent);
		long startTime, endTime;
		startTime = System.currentTimeMillis();
		
		boolean isSucc = false;

		PdfStamper stamp = null;
		try {
			// 获取PDF总页数信息
			PdfReader pdfReader = new PdfReader(new FileInputStream(InPdfFile));
			int pageSize = pdfReader.getNumberOfPages();
			log.debug("PDFHelper.addPdfMark 总页数:" + pageSize);

			PdfReader reader = new PdfReader(InPdfFile, "PDF".getBytes());
			stamp = new PdfStamper(reader, new FileOutputStream(outPdfFile));

			// 插入水印
			Image img = Image.getInstance(markImagePath);

			// 设置图片位置和缩放比例
			img.setAbsolutePosition(xCoord, yCoord);
			img.scalePercent(scalePercent);

			// 开始循环添加水印图片
			for (int i = 1; i <= pageSize; i++) {
				PdfContentByte under = stamp.getOverContent(i);
				under.addImage(img);
			}

			File dirAll = new File(outPdfFile);
			// 检查目标文件是否存在
			if (!dirAll.exists()) {
				isSucc = false;
			} else {
				isSucc = true;
			}
			log.debug("PDFHelper.addPdfMark 执行操作完成-" + isSucc);

		} catch (Exception e) {
			isSucc = false;
			log.error("PDFHelper.addPdfMark Exception:", e);

		} finally {
			// 关闭文件流
			try {
				stamp.close();
			} catch (DocumentException e) {
				log.error("PDFHelper.addPdfMark 关闭文件流 DocumentException:", e);
				e.printStackTrace();
			} catch (IOException e) {
				log.error("PDFHelper.addPdfMark 关闭文件流 IOException:", e);
			}

			endTime = System.currentTimeMillis();
			log.debug("PDFHelper.addPdfMark Return Result:" + isSucc + " UseTime:" + (endTime - startTime) + "(ms)");
		}
		return isSucc;
	}

	/**
	 * 合并PDF方法
	 * 
	 * @param pdfFilenames   待合并PDF文件
	 * @param targetFilename 合并后目标文件
	 * @return 操作成功或失败
	 */
	public static boolean combinPdf(List<String> pdfFilenames, String targetFilename) {

		log.debug("PDFHelper.combinPdf 调用参数信息:" + " pdfFilenames[]:" + pdfFilenames.toString() + " targetFilename:" + targetFilename);
		long startTime, endTime;
		startTime = System.currentTimeMillis();
		
		boolean isSucc = false;

		Document doc = new Document();

		try {
			PdfReader reader = null;
			PdfCopy pdfCopy = new PdfCopy(doc, new FileOutputStream(targetFilename));
			int pageCount = 0;
			doc.open();
			for (int i = 0; i < pdfFilenames.size(); ++i) {
				log.debug("PDFHelper.combinPdf 当前合并文件位置:" + i + " FileName:" + pdfFilenames.get(i));
				reader = new PdfReader(pdfFilenames.get(i).toString());
				pageCount = reader.getNumberOfPages();
				for (int j = 1; j <= pageCount; ++j) {
					pdfCopy.addPage(pdfCopy.getImportedPage(reader, j));
				}
			}
			isSucc = true;
			log.debug("PDFHelper.combinPdf 合并操作完成!");

		} catch (Exception e) {
			isSucc = false;
			log.error("PDFHelper.combinPdf Exception:", e);
		} finally {
			try {
				doc.close();
			} catch (Exception e2) {
				log.error("PDFHelper.combinPdf close Exception:", e2);
			}

			endTime = System.currentTimeMillis();
			log.debug("PDFHelper.combinPdf Return Result:" + isSucc + " UseTime:" + (endTime - startTime) + "(ms)");
		}

		return isSucc;
	}

}